﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace MyInfrastructure.Repository
{
	public abstract class Repository<TEntity, TKey> : IRepository<TEntity, TKey> where TEntity : class
	{
		private readonly DbContext _context;

		protected Repository(DbContext context)
		{
			_context = context;
		}
		public int Commit()
		{
			return _context.SaveChanges();
		}

		public async Task<int> CommitAsync()
		{
			return await _context.SaveChangesAsync();
		}

		public void Dispose()
		{
			//_context.SaveChanges();   自动提交
			_context.Dispose();
		}

		public void Add(TEntity entity)
		{
			_context.Set<TEntity>().Add(entity);
		}

		public void AddRange(IEnumerable<TEntity> entities)
		{
			_context.Set<TEntity>().AddRange(entities);

		}

		public void Delete(TEntity entity)
		{

			_context.Set<TEntity>().Remove(entity);
		}

		public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
		{

			return _context.Set<TEntity>().Where(predicate).AsEnumerable();
		}

		public TEntity Get(TKey id)
		{
			return _context.Set<TEntity>().Find(id);
		}

		public IEnumerable<TEntity> GetAll()
		{
			return _context.Set<TEntity>().AsEnumerable();
		}

		public void Update(TEntity entity)
		{
			_context.Set<TEntity>().Update(entity);
		}
	}
}
